const fs = require('fs');
const { ipcRenderer, shell } = require('electron');

// let lnk = shell.readShortcutLink('C:/Users/Administrator/Desktop/test.lnk');
// let { program: programData } = require("./assets/js/data/desktop.js");

var programData = [];
var winFlag = [];
let { taskbarDom } = require("./assets/js/taskbar.js");
let { getDycalendar } = require("./assets/js/dycalendar.js");
let { getLunar } = require("./assets/js/data/tools/getDayName.js");
let { imgPath, programFn, contextMenuFn } = require("./assets/js/data/config.js");
let { contextMenu: contextMenuData } = require('./assets/js/data/contextMenu.js');
let { tools } = require("./assets/js/utils/util.js");
console.time("a");

// 使用代理做响应式数据
let cssProxyData = new Proxy({}, {
    set(target, property, newVal, receiver) {
        target[property] = newVal;
        return (tools.myTypeOf(proxyHooks[property]) == 'Function') && proxyHooks[property](target, property, newVal, receiver);
    }
});
let proxyHooks = {// 响应式数据拦截
    ['--lP-font-color'](target, property, newVal, receiver) {
        document.documentElement.style.setProperty(property, newVal);
        return true;
    }
};

// 加载json文件
let jsonDataArr = [
    { fileName: 'desktop', field: 'programData' },
    { fileName: 'WinFlag', field: 'winFlag' }
];
jsonDataArr.map((e, i) => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', `./assets/json/${e.fileName}.json`, false); // 同步请求
    xhr.send();
    if (xhr.status === 200) {
        window[e.field] = JSON.parse(xhr.responseText);
    } else {
        console.error('Failed to load data');
    };
});

window.onunload = function () {
    // 保存桌面程序的修改
    let str = `${JSON.stringify(programData)}`;
    fs.writeFileSync('assets/json/desktop.json', str);
    fs.writeFileSync('assets/json/WinFlag.json', JSON.stringify(winFlag));
};

window.onload = function () {
    let dycalendarDate = dqS('.rightContext .dycalendar .top .date');
    let scrollTarget = dqS(`.rightContext .dycalendar .tableBox .div[data-cur-date="${dycalendarDate.innerText}"]`);
    scrollTarget.scrollIntoView();
    // console.log(rightContext.offsetWidth, `translateX(${20 + rightContext.offsetWidth}px)`);
    // rightContext.style.transform = `translateX(${20 + rightContext.offsetWidth}px)`;
};

function dqS(selector) {
    return document.querySelector(selector);
};
function dqSAll(selector) {
    return document.querySelectorAll(selector);
};
// 全局变量
let promiseList = [];
let body = dqS(".win");
let mouseSelectBox = dqS(".mouse-select-box");
let wallpaper = document.createElement('img');
let contextMenu = dqS('.contextMenu');
let canDefault = {// 管理阻止默认事件触发的对象
    document: {
        click: false,
        dblclick: false,
        mouseover: false,
        mouseout: false,
        mousedown: false,
        mouseup: false,
        mousemove: false,
        drop: false,
        dragover: false,
    }
};
let timer = {// 管理定时器的对象
    programRenameTimer: null,
    programReloadTimerArr: [],
};
// let promiseRes = {// 管理promise函数执行
//     programReloadRes: {
//         resolve: null,
//         reject: null
//     },
// };

let promiseResArr = [];// 管理promise函数执行

// 桌面背景图加载
let [wallpaperCopy, wallpaper2] = [null, null];
let wallpaperRootDir = 'assets/image/wallpaper';
let wallpaperDir = fs.readdirSync(wallpaperRootDir).reduce((p, e, i, s) => p.concat(e == "touchkeyboard" ? fs.readdirSync(`${wallpaperRootDir}/${e}`)
    .map(ee => `${wallpaperRootDir}/${e}/${ee}`) : [`${wallpaperRootDir}/${e}`]), []);

wallpaper.classList.add('wallpaper');

wallpaper.src = imgPath + `${wallpaperRootDir}/img27.jpg`;
promiseList.push(new Promise((resolve, reject) => {
    wallpaper.onload = function (e) {
        wallpaperCopy = wallpaper.cloneNode(true);
        wallpaper.classList.add('wallpaper-clip');
        wallpaperCopy.classList.add('wallpaper-copy');
        wallpaper2 = wallpaper.cloneNode(true);
        wallpaper2.classList.add('wallpaper2');
        wallpaper2.style.zIndex = '-7';
        body.append(wallpaper);
        body.append(wallpaper2);
        body.append(wallpaperCopy);
        resolve("wallpaper");
    };
}));

async function cutWallpaperLoop(ms = 10 * 1000, ind = 0) {// 桌面背景自动轮播(默认每隔十秒钟切换一次)
    let val = await new Promise((resolve, reject) => {
        setTimeout(() => {
            if (ind >= wallpaperDir.length) ind = 0;
            // ind % 2 == 0 ? (wallpaper2.src = imgPath + wallpaperDir[ind]) : (wallpaper.src = imgPath + wallpaperDir[ind]);
            // wallpaper.onload = function (e) {
            //     wallpaper.style.opacity = 1;
            //     wallpaper2.style.opacity = 0;
            //     wallpaperCopy.src = wallpaper.src;
            //     resolve(ind + 1);
            // };
            // wallpaper2.onload = function (e) {
            //     wallpaper.style.opacity = 0;
            //     wallpaper2.style.opacity = 1;
            //     wallpaperCopy.src = wallpaper2.src;
            //     resolve(ind + 1);
            // };

            // 代码量简化⬆️
            let arr = [wallpaper, wallpaper2];
            arr[(ind + 1) % 2].src = imgPath + wallpaperDir[ind];
            arr.map((el, i) => {
                el.onload = function (event) {
                    el.style.opacity = (i + ind) % 2;
                    arr[(ind) % 2].style.opacity = (i + ind + 1) % 2;
                    wallpaperCopy.src = el.src;
                    resolve(ind + 1);
                };
            });
        }, ms);
    });

    cutWallpaperLoop(ms, val);
};
winFlag[0].open && cutWallpaperLoop();
// body.style.backgroundImage = 'url("./assets/image/wallpaper/img25.jpg")';
// body.style.backgroundImage = 'url("https://chen88520.gitee.io/picture-cdn/assets/image/wallpaper/img25.jpg")';

// 右侧内容模块
function renderRightContext() {
    let newDate = new Date();

    let dycalendarBoxTopDate1 = dqS(".rightContext .dycalendarBoxTop .left .date1");
    let dycalendarBoxTopDate2 = dqS(".rightContext .dycalendarBoxTop .left .date2");
    let dycalendarBoxTopRightImg = dqS(".rightContext .dycalendarBoxTop .rightImg");
    dycalendarBoxTopDate1.innerText = `${newDate.getMonth() + 1}月${newDate.getDate()}日,${tools.num2weekDay(newDate.getDay(), '星期')}`;
    dycalendarBoxTopDate2.innerText = `${getLunar(newDate)}`;
    dycalendarBoxTopRightImg.src = `${imgPath}/assets/image/svg/bottom-fff.svg`;

    renderDycalendarTable();

    let dycalendarBoxBottomLeft = dqS('.rightContext .dycalendarBox .bottom .left');
    let dy_minute = dycalendarBoxBottomLeft.children[1];
    dy_minute.innerText = `30 分钟`;
    let dy_tempArr = [dycalendarBoxBottomLeft.children[0], dycalendarBoxBottomLeft.children[2]];
    dy_tempArr.map((ele, ind) => {
        let arr = [{ minus: '-' }, { plus: '+' }];
        for (const key in arr[ind]) {
            ele.firstChild.src = `${imgPath}/assets/image/svg/${key}.svg`;
            ele.addEventListener('mousedown', function (event) {
                let num = parseInt(dy_minute.innerText);
                if ((num == 5 && ind === 0) || (num == 240 && ind === 1)) return;
                let addNum = 0;
                addNum = num < 30 ? 5 : 15;
                num = num + parseInt(arr[ind][key] + addNum);
                dy_minute.innerText = `${num} 分钟`;
            });
        };
    });
    let dycalendarBoxBottomright = dqS('.rightContext .dycalendarBox .bottom .right');
    dycalendarBoxBottomright.children[0].src = `${imgPath}/assets/image/svg/triangle.svg`;

};

function renderDycalendarTable(date = new Date()) {
    let dycalendarDate = dqS('.rightContext .dycalendar .top .date');
    const renderDycalendarDate = (date) => {
        dycalendarDate.innerText = `${date.getFullYear()}年${date.getMonth() + 1}月`;
    };
    renderDycalendarDate(date);

    let { table, getprevData, getnextData } = getDycalendar(date);

    let arr = ['prev', 'next'];
    let fun = { getprevData, getnextData };
    arr.map((field, type) => {
        let el = dqS('.rightContext .dycalendar .top .btns img.' + field);
        el.src = `${imgPath}/assets/image/svg/triangle.svg`;
        el.parentNode.addEventListener('mousedown', function (event) {
            let add = type ? type : -1;
            // // let oldMonth = date.innerText.match(/年(.*)月/)[1] - 1;
            let oldMonth = parseInt(dycalendarDate.innerText.slice(5, -1)) - 1;
            // let newDate = tools.changeDate([date, 'setMonth', true], oldMonth + add);
            let newDate = tools.changeDate([date, '', true]);
            newDate.setDate(1);
            newDate.setMonth(oldMonth + add);
            date = newDate;
            renderDycalendarDate(newDate);

            let targetArr = new Array(...dqSAll(`.rightContext .dycalendar .tableBox .div[data-cur-date]`));
            let condition1 = targetArr[1].dataset.curDate == dycalendarDate.innerText;
            let condition2 = targetArr.at(-2).dataset.curDate == dycalendarDate.innerText;
            console.log(targetArr[1].dataset.curDate, dycalendarDate.innerText, targetArr.at(-2).dataset.curDate);
            // if (condition1 || condition2) {
            //     let nowStr = document.querySelector('.rightContext .dycalendar .top .date');
            //     let now = new Date(nowStr.innerText.replace(/[\u4e00-\u9fa5]/g, '-').slice(0, -1));
            //     fun[`get${field}Data`](now);
            // };
            let scrollTarget = dqS(`.rightContext .dycalendar .tableBox .div[data-cur-date="${dycalendarDate.innerText}"]`);
            scrollTarget.scrollIntoView({ behavior: "smooth" });
        });
    });


    let tableBox = dqS('.tableBox');
    tableBox.append(table);
};

renderRightContext();
// let day = new Date();
// for (let index = -1; index < 2; index++) renderDycalendarTable(tools.changeDate([day, 'setMonth', true], day.getMonth() + index));

// 挂载任务栏
body.append(taskbarDom);

// 桌面模块
let desktop = dqS('.desktop');
let programBox = dqS('.program-box');
function loadName(name, val) {// 渲染程序名
    name.classList.add("name");
    name.innerText = val;
    name.nextElementSibling && (name.nextElementSibling.innerText = val);
    let nameStrArr = val.match(/\w*/g).filter(e => !!e);
    if (nameStrArr.some(e => e.length >= 8)) {
        name.style["-webkit-line-clamp"] = "1";
        name.style["word-break"] = "break-all";
    } else {
        name.style["-webkit-line-clamp"] = "";
        name.style["word-break"] = "";
    };
};
function loadDesktop() {// 渲染桌面程序
    // console.log("loadDesktop");

    contextMenu.className = 'contextMenu hide';
    programBox.innerHTML = "";

    programData.map((e, ind) => {
        let program = document.createElement('div');
        let programDiv = document.createElement('div');
        program.classList.add('program');
        programDiv.addEventListener('mouseenter', (ele) => {
            // 程序拖拽
            let programCopy = dqS('.program-copy');
            if (programCopy) {
                ele.target.parentNode.style['border-bottom'] = '3px ridge #f0f0f0';
            };
        });
        programDiv.addEventListener("mouseleave", (ele) => {
            dqSAll(".program").forEach((element, index) => {
                element.style['border-bottom'] = '';
            });
        });
        programDiv.addEventListener("mouseup", (ele) => {
            let programCopy = dqS('.program-copy');
            if (programCopy) {
                let eleInd = ele.target.dataset.ind;
                let programCopyInd = programCopy.dataset.ind;
                if (eleInd != programCopyInd) {
                    if (programData[eleInd].special) {// 特殊程序
                        if (programData[eleInd].special == 'Recycle Bin') {// 回收站
                            programData.splice(programCopyInd, 1);
                        };
                    } else {
                        [programData[eleInd], programData[programCopyInd]] = [programData[programCopyInd], programData[eleInd]];
                    };
                    if (timer.programReloadTimerArr.at(-1)) {
                        clearTimeout(timer.programReloadTimerArr.at(-1));
                        timer.programReloadTimerArr.splice(timer.programReloadTimerArr.length - 1);
                    };
                    timer.programReloadTimerArr.push(setTimeout(loadDesktop, 186));
                };
            };
        });
        programDiv.addEventListener("mousedown", (ele) => {
            if (ele.button == 2) {
                console.log("程序右键", ele);
                ele.stopPropagation();
            };
        });
        programDiv.classList.add('program-div');
        program.dataset.ind = ind;
        programDiv.dataset.ind = ind;

        /* let programHtml = `
            <img class="svgIcon" src="assets/image/${e.icon}" alt="">
            <div class="name">${e.name}</div>
        `; */

        /* let programHtml = `
            <img class="svgIcon" onload="programDataLoad" src="https://chen88520.gitee.io/picture-cdn/assets/image/${e.icon}" alt="">
            <div class="name">${e.name}</div>
        `; */
        let svgIcon = document.createElement("img");
        svgIcon.classList.add("svgIcon");
        svgIcon.src = e.icon ? `${imgPath}/assets/image/${e.icon}` : e.icon2;
        svgIcon.dataset.ind = ind;
        promiseList.push(new Promise((resolve, reject) => {
            svgIcon.onload = function (event) {
                resolve(e.name);
            };
        }));
        programDiv.append(svgIcon);

        let name = document.createElement("div");
        name.dataset.ind = ind;
        loadName(name, e.name);
        programDiv.append(name);

        let ipt = document.createElement('div');
        ipt.classList.add("rename");
        ipt.innerText = e.name;
        ipt.dataset.ind = ind;
        ipt.onblur = function (e) {
            let name = this.previousSibling;
            let str = this.innerText.trim().length != 0 ? this.innerText : name.innerText;
            programData[e.target.dataset.ind].name = str;
            loadName(name, str);
        };
        // ipt.onfocus = function () {
        //     console.log(this, 'onfocus');
        // };
        setTimeout(() => {
            ipt.style.top = name.offsetTop + 'px';
        }, 1000);
        ipt.setAttribute('contenteditable', "true");
        programDiv.append(ipt);
        program.append(programDiv);
        programBox.append(program);
    });
    desktop.append(programBox);
};
loadDesktop();

// loading界面模块
let welcomePage = dqS(".welcome");
let welcomeLoading = dqS(".welcome-loading");
for (let index = 0; index < 16; index++) {
    let loadingDiv = document.createElement('div');
    let round = document.createElement('div');
    loadingDiv.classList.add("loading-box");
    loadingDiv.style.transform = `translateX(-50%) rotate(${360 / 16 * index}deg)`;
    loadingDiv.style.opacity = `${1 / 16 * index}`;
    round.classList.add("round");
    loadingDiv.append(round);
    welcomeLoading.append(loadingDiv);
};

// 登录页模块
function loadLP(flag) {
    let loginPage = dqS('.login-page');
    if (flag) return loginPage.style.display = 'none';
    // cssProxyData['--lP-font-color'] = '#fff';
    let lP_bgi = dqS('.login-page .bgi');
    lP_bgi.src = imgPath + "/assets/image/wallpaper/img100.jpg";
    let lP_img1 = dqS('.login-page .page2 .password-box .preview-open');
    lP_img1.src = imgPath + "/assets/image/svg/preview-open.svg";
    let lP_img2 = dqS('.login-page .page2 .password-box .arrow-right');
    lP_img2.src = imgPath + "/assets/image/svg/arrow-right.svg";
    let avatarImg = dqS('.login-page .page2 .avatar-img ');
    avatarImg.src = imgPath + "/assets/image/svg/people.svg";
    let lP_obj = { lP_bgi, lP_img1, lP_img2, avatarImg };
    for (const key in lP_obj) {
        promiseList.push(new Promise((resolve, rejcet) => {
            lP_obj[key].onload = function () {
                resolve(key);
            };
        }));
    };

    let lP_page1 = dqS('.login-page .page1');
    let currND = new Date();
    let currDate = currND.toLocaleDateString().split('/').slice(-2).map((e, i) => i == 0 ? e.padStart(2, '0') + '月' : e.padStart(2, '0') + '日').join('');
    let currTime = currND.toLocaleTimeString().slice(0, -3);
    let currWeek = tools.num2weekDay(currND.getDay(), '星期');
    lP_page1.children[0].innerText = currTime;
    lP_page1.children[1].innerText = [currDate, currWeek].join();

    let lP_page2 = document.querySelector('.login-page .page2');
    lP_page2.style.display = 'none';

    let loginIpt = dqS('.login-page .page2 .login-ipt');

    let passwordError = dqS('.login-page .page2 .password-error');
    passwordError.style.display = 'none';

    let resetPasswordIpt = dqS('.login-page .page2 .reset-password-ipt');
    resetPasswordIpt.style.display = 'none';
    let reIpts = resetPasswordIpt.children;
    let cancelRePassword = resetPasswordIpt.lastElementChild;
    [
        { 1: imgPath + "/assets/image/svg/preview-open.svg" },
        { 1: imgPath + "/assets/image/svg/preview-open.svg" },
        { 1: imgPath + "/assets/image/svg/preview-open.svg" },
        { 1: imgPath + "/assets/image/svg/arrow-right.svg" },
    ].map((ele, ind) => {
        for (const key in ele) {
            reIpts[ind].children[key].src = ele[key];
        };
    });

    let arrowRight = dqS('.login-page .page2 .login-ipt .arrow-right');
    let arrowRight2 = dqS('.login-page .page2 .reset-password-ipt .arrow-right');
    arrowRight2.style.opacity = 1;

    let loginBtn = dqS('.login-page .page2 .password-error .btn');
    let lp_password = dqSAll('.login-page .page2 .password');

    let passwordReset = dqS('.login-page .page2 .login-ipt .password-reset');
    let lp_userName = dqS('.login-page .page2 .userName');
    lp_userName.innerText = winFlag[0].user;

    let createRePassword = dqS('.login-page .page2 .reset-password-ipt .password-reset');
    let lP_tips = dqSAll('.login-page .page2 .password-tips');
    lP_tips[0].innerText = `密码提示: ${winFlag[0].tips}`;
    lP_tips[1].innerText = `密码不正确。请再输入一次。`;

    function lP_userLogin(val) {// win登录
        if (val != winFlag[0].password) {
            loginIpt.style.display = 'none';
            passwordError.style.display = '';
            loginBtn.dataset.namefn = 'lp_password-0';
        } else {
            winFlag[0].open = true;
            loginPage.classList.add('hide');
            cutWallpaperLoop();
        };
    };

    function lP_rePassword() {// 重置密码
        let showTips = '';
        let namefn = 'lp_password-1';
        if (lp_password[1].value != winFlag[0].password) {
            showTips = '密码不正确。请再输入一次。';
        } else {
            if (lp_password[2].value != lp_password[3].value) {
                showTips = '您输入的密码不匹配。';
            } else {
                winFlag[0].tips = lp_password[4].value;
                winFlag[0].password = lp_password[2].value;
                lP_tips[0].innerText = `密码提示: ${winFlag[0].tips}`;
                namefn = 'lp_password-2';
                showTips = '您的密码已更改。';
            };
        };
        lP_tips[1].innerText = showTips;
        resetPasswordIpt.style.display = 'none';
        passwordError.style.display = '';
        loginBtn.dataset.namefn = namefn;
    };

    lp_password.forEach((element) => {// 表单事件
        let previewOpen = element.nextElementSibling;
        element.addEventListener('input', function (event) {
            if (![].includes.call(previewOpen.classList, 'arrow-right')) {
                previewOpen.style.opacity = this.value.length;
                previewOpen.addEventListener('mousedown', function (event) {
                    element.setAttribute('type', 'text');
                });

                previewOpen.addEventListener('mouseup', function (event) {
                    element.setAttribute('type', 'password');
                });
            };
        });
    });

    passwordReset.addEventListener('mousedown', function (event) {// 显示重置密码界面
        resetPasswordIpt.style.display = '';
        loginIpt.style.display = 'none';
        lp_password[4].value = winFlag[0].tips;
    });

    cancelRePassword.addEventListener('mousedown', function (event) {// 取消重置密码
        lp_password.forEach(element => element.value = '');
        resetPasswordIpt.style.display = 'none';
        loginIpt.style.display = '';
    });

    arrowRight.addEventListener('mousedown', function (event) {// 登录win
        lP_userLogin(lp_password[0].value);
    });

    arrowRight2.addEventListener('mousedown', function (event) {// 重置密码
        lP_rePassword();
    });

    createRePassword.addEventListener('mousedown', function (event) {
        alert('此功能需要可移动介质，如USB闪存驱动器。请连接U盘，然后再试一次。');
    });

    loginBtn.addEventListener('mousedown', function (event) {// 错误界面按钮
        switch (event.target.dataset.namefn) {
            case 'lp_password-0':
                passwordError.style.display = 'none';
                lp_password[0].value = '';
                loginIpt.style.display = '';
                break;
            case 'lp_password-1':
                passwordError.style.display = 'none';
                lp_password.forEach(element => element.value = element.className.includes('word-tips') ? element.value : '');
                resetPasswordIpt.style.display = '';
                break;
            case 'lp_password-2':
                passwordError.style.display = 'none';
                lp_password.forEach(element => element.value = '');
                resetPasswordIpt.style.display = 'none';
                loginIpt.style.display = '';
                break;

            default:
                break;
        }
    });

    loginPage.addEventListener('mousedown', function (event) {
        if (![].includes.call(lP_bgi.classList, 'blur15')) {
            lP_bgi.classList.add('blur15');
            lP_page1.style.display = 'none';
            lP_page2.style.display = '';
        };
        // 阻止冒泡到document
        event.stopPropagation();
    });

    loginPage.addEventListener("keydown", function (event) {
        if (event.key == 'Enter') {
            lP_userLogin(lp_password[0].value);
        };
        // 阻止冒泡到document
        event.stopPropagation();
    });

};
loadLP(winFlag[0].open);

function mouseSelectBoxFN() {// 鼠标选择框函数
    let program = dqSAll('.program>div');
    let mouseSelectBoxCoordinate = getComputedStyle(mouseSelectBox)['clip-path'].match(/-?\d*px -?\d*px/g);
    let [a, b, c, d] = mouseSelectBoxCoordinate;
    let [px1, py1] = a.split(" ").map(e => +e.slice(0, -2));
    let [px2, py2] = c.split(" ").map(e => +e.slice(0, -2));
    let minX = (px1 - px2) > 0 ? px2 : px1;
    let maxX = (px1 - px2) > 0 ? px1 : px2;
    let minY = (py1 - py2) > 0 ? py2 : py1;
    let maxY = (py1 - py2) > 0 ? py1 : py2;
    let midX = (maxX + minX) / 2;
    let midY = (maxY + minY) / 2;

    let rect2 = {
        offsetLeft: minX,
        offsetWidth: maxX - minX,
        offsetTop: minY,
        offsetHeight: maxY - minY
    }

    program.forEach(el => {
        let { offsetHeight, offsetLeft, offsetTop, offsetWidth } = el;
        let rect1 = { offsetHeight, offsetLeft, offsetTop, offsetWidth };
        el.style.background = tools.isCollision_rect(rect1, rect2) ? "rgba(255, 255, 255, 0.233)" : "";
    });
};

function openExplorer() {// 打开资源管理器
    alert("暂未开发！");
};

function openProgram(program) {// 打开程序
    // console.log(program);
    if (programFn[program.nameFN]) {
        programFn[program.nameFN](program.payload);
    } else {
        if (confirm("暂未配置该程序！可以下载源码，然后再assets/js/data/config.js文件里配置，有问题可以加我微信:19924343977，源码地址：https://gitee.com/chen88520/electron-win11")) {
            window.open("https://gitee.com/chen88520/electron-win11");
        } else {
            alert("如果您的电脑有该软件，也可以拖拽导入哦！");
        };
    };
};

function dblclickFN(ind) {// dblclick函数 
    clearTimeout(timer.programReloadTimerArr.at(-1));
    timer.programReloadTimerArr.splice(timer.programReloadTimerArr.length - 1);

    let program = programData[ind];
    if (program.type == "explorer") {
        openExplorer();
    };
    if (program.type == "program") {
        openProgram(program);
    };
};

function loadContextmenu(ele, type) {// 加载操作菜单
    contextMenu.innerHTML = '';
    let { pageX, pageY } = ele;
    let dataBox = contextMenuData[type];
    if (dataBox) {// 渲染菜单
        dataBox.map((dataBoxItem, i) => {
            let menuBox = document.createElement('div');
            menuBox.classList.add("menu-box");
            dataBoxItem.map((item, ii) => {
                let menuItem = document.createElement('div');
                menuItem.classList.add("menu-item");
                menuItem.addEventListener('mousedown', event => {
                    // console.log('菜单左键');
                    try {
                        contextMenuFn[item.handleClickName]({ loadDesktop, programBox, contextMenu });
                    } catch (error) {
                        alert('暂未开发！');
                        throw error;
                    };
                    event.stopPropagation();
                });

                let operate = document.createElement('div');
                operate.classList.add("operate");

                let icon = document.createElement('div');
                let iconImg = document.createElement('img');
                icon.classList.add("icon");
                iconImg.src = `${imgPath}/assets/image/${item.icon}`;
                icon.append(iconImg);

                let label = document.createElement('div');
                label.classList.add("label");
                label.innerText = item.label

                let right = document.createElement('div');
                right.classList.add("right");
                if (item.rightText) {
                    let rightText = document.createElement('div');
                    rightText.innerHTML = item.rightText;
                    right.append(rightText);
                } else if (item.rightIcon) {
                    let rightIcon = document.createElement('img');
                    rightIcon.src = `${imgPath}/assets/image/${item.rightIcon}`;
                    right.append(rightIcon);
                };

                let rightContext = document.createElement('div');
                rightContext.classList.add("rightContext");

                menuItem.append(operate, icon, label, right, rightContext);
                menuBox.append(menuItem);
            });
            contextMenu.append(menuBox);
        });
        let { clientHeight: bodyH, clientWidth: bodyW } = programBox;
        let { clientHeight: menuH, clientWidth: menuW } = contextMenu;
        let condition1 = pageX + menuW > bodyW;
        let condition2 = pageY + menuH > bodyH;
        if (condition1 && condition2) {
            contextMenu.style.left = pageX - menuW + 'px';
            contextMenu.style.top = pageY - menuH + 'px';
        } else if (condition1) {
            contextMenu.style.left = pageX - menuW + 'px';
            contextMenu.style.top = pageY + 'px';
        } else if (condition2) {
            contextMenu.style.left = pageX + 'px';
            contextMenu.style.top = pageY - menuH + 'px';
        } else {
            contextMenu.style.left = pageX + 'px';
            contextMenu.style.top = pageY + 'px';
        };
        contextMenu.className = "contextMenu show";
    };
};

// document事件
document.addEventListener('click', function (e) {
    let { pageX, pageY } = e;

    // console.log("click", e);
    !canDefault.document[e.type] && e.preventDefault();
});

document.addEventListener('dblclick', function (e) {

    // 打开桌面程序
    if (
        ['svgIcon', 'name'].includes(e.target.className)
        && e.target.parentNode.className == "program-div"
    ) {
        clearTimeout(timer.programRenameTimer);
        dblclickFN(e.target.parentNode.dataset.ind);
    };
    if (e.target.className == "program-div") {
        // 取消桌面程序重命名Timer
        clearTimeout(timer.programRenameTimer);
        dblclickFN(e.target.dataset.ind);
    };

    // console.log("dblclick", e);
    !canDefault.document[e.type] && e.preventDefault();
});

document.addEventListener('mouseover', function (e) {

    // 错误提示框
    if (e.target.className == 'btn ok' && e.target.dataset.isDown == "true") {// 确定按钮
        e.target.style.top = '2px';
        e.target.style.left = '2px';
        e.target.previousElementSibling.style.display = 'none';
    };
    if (tools.isParentNodeEl(e.target, dqS(".error-tips .top .close-box"))) {// 关闭按钮
        dqS(".error-tips .top .close:nth-of-type(1)").style.display = "none";
        dqS(".error-tips .top .close:nth-of-type(2)").style.display = "none";
        dqS(".error-tips .top .close:nth-of-type(3)").style.display = "block";
    };

    // console.log("mouseover",e);
    !canDefault.document[e.type] && e.preventDefault();
});

document.addEventListener('mouseout', function (e) {

    // 错误提示框
    if (e.target.className == 'btn ok' && e.target.dataset.isDown == "true") {// 确定按钮
        e.target.style.top = '';
        e.target.style.left = '';
        e.target.previousElementSibling.style.display = '';
    };
    if (tools.isParentNodeEl(e.target, dqS(".error-tips .top .close-box"))) {// 关闭按钮
        let flag = getComputedStyle(dqS(".error-tips .top")).color == 'rgb(0, 0, 0)';
        dqS(".error-tips .top .close:nth-of-type(1)").style.display = flag ? "block" : "none";
        dqS(".error-tips .top .close:nth-of-type(2)").style.display = flag ? "none" : "block";
        dqS(".error-tips .top .close:nth-of-type(3)").style.display = "none";
    };

    // console.log("mouseout",e);
    !canDefault.document[e.type] && e.preventDefault();
});

document.addEventListener('mousedown', function (e) {
    let { pageX, pageY } = e;
    let programList = dqSAll('.program-div');
    let program = programList[e.target.dataset.ind];

    if (["desktop", "program", "program-div", "program-box", "svgIcon", 'name'].includes(e.target.className)) {

        if (tools.isParentNodeEl(e.target, program)) {// 桌面程序拖拽初始化
            let programCopy = program.cloneNode(true);
            let parentNode = program.parentNode;
            programCopy.style.top = program.offsetTop + 'px';
            programCopy.style.left = program.offsetLeft + 'px';
            programCopy.style['z-index'] = '-1';
            programCopy.classList.add('bg_transparent');
            programCopy.classList.add('program-copy');
            programCopy.dataset.ind = e.target.dataset.ind;
            programCopy.dataset.coordinate = JSON.stringify({ initX: pageX, initY: pageY });
            parentNode.append(programCopy);
        } else {// 桌面鼠标选择框
            mouseSelectBox.style.display = "block";
        };
        mouseSelectBox.dataset.coordinate = JSON.stringify({ initX: pageX, initY: pageY });
        mouseSelectBoxFN();



        // 桌面程序一些初始操作
        programList.forEach(el => {// 隐藏重命名框
            if (tools.isParentNodeEl(e.target, el)) return;
            el.childNodes[1].style.visibility = "";
            el.childNodes[2].style.display = '';
            el.dataset.isSelect = "false";
            canDefault.document.mousedown = false;
            canDefault.document.mousemove = false;
        });
    };

    // 选择桌面程序
    if (
        ['svgIcon', 'name'].includes(e.target.className)
        && e.target.parentNode.className == "program-div"
    ) {
        e.target.parentNode.style.background = "rgba(255, 255, 255, 0.3)";
        if (e.target.className == "name") {
            if (e.target.parentNode.dataset.isSelect == "true") {// 程序重命名
                clearTimeout(timer.programRenameTimer);
                timer.programRenameTimer = setTimeout(() => {
                    canDefault.document.mousedown = true;
                    canDefault.document.mousemove = true;
                    e.target.style.visibility = "hidden";
                    e.target.nextElementSibling.style.display = "flex";
                    // 光标聚焦
                    // let ipt = document.createElement('textarea');
                    // e.target.nextElementSibling.focus();
                    // let len = e.target.nextElementSibling.innerText.length;
                    // tools.setCaretPosition(e.target.nextElementSibling.lastChild, len - 1);
                    // console.log(window.getSelection());
                }, 186);
            } else {

            };
        } else {

        };
        e.target.parentNode.dataset.isSelect = "true";
    };
    if (e.target.className == "program-div") {
        e.target.style.background = "rgba(255, 255, 255, 0.3)";
        e.target.dataset.isSelect = "true";
    };

    // 错误提示框
    if (e.target.className == 'btn ok') {// 确定按钮
        e.target.style.top = '2px';
        e.target.style.left = '2px';
        e.target.previousElementSibling.style.display = 'none';
        e.target.dataset.isDown = 'true';
    };
    if (tools.isParentNodeEl(e.target, dqS('.error-tips'))) {// 点击错误提示框
        dqS(".error-tips .top").style.color = '#000';
        dqS(".error-tips .top .close:nth-of-type(1)").style.display = "block";
        dqS(".error-tips .top .close:nth-of-type(2)").style.display = "none";
        dqS(".error-tips .top .close:nth-of-type(3)").style.display = "none";
        dqS(".error-tips .btns .background").style.border = "1px solid #000";
    } else {
        dqS(".error-tips .top").style.color = '#919191';
        dqS(".error-tips .top .close").style.display = "none";
        dqS(".error-tips .top .close:nth-of-type(1)").style.display = "none";
        dqS(".error-tips .top .close:nth-of-type(2)").style.display = "block";
        dqS(".error-tips .top .close:nth-of-type(3)").style.display = "none";
        dqS(".error-tips .btns .background").style.border = "";
    };

    // console.log("mousedown", e);
    !canDefault.document[e.type] && e.preventDefault();
});

document.addEventListener('mouseup', function (e) {
    // 桌面鼠标选择框
    mouseSelectBox.style.display = "";
    mouseSelectBox.style['clip-path'] = "";

    // 错误提示框确定按钮
    let btnOk = dqS(".error-tips .btns .btn");
    btnOk.style.top = '';
    btnOk.style.left = '';
    btnOk.previousElementSibling.style.display = '';
    btnOk.dataset.isDown = 'false';

    // 桌面程序拖拽
    let programCopy = dqS('.program-copy');
    if (programCopy) {
        let parentNode = programCopy.parentNode;
        let { top, left, transform } = programCopy.style;
        left = +left.slice(0, -2);
        top = +top.slice(0, -2);
        let [translateX = 0, translateY = 0] = transform.match(/-?\d*px/g)?.map(el => +el.slice(0, -2)) || [];
        let { offsetLeft = 0, offsetTop = 0 } = dqSAll('.program-div')[e.target.dataset.ind] || {};
        // console.log(left + translateX, top + translateY, { offsetLeft, offsetTop });
        parentNode.removeChild(programCopy);
    };

    // 右击事件
    if (e.button == 2 && !tools.isParentNodeEl(e.target, contextMenu)) {
        contextMenu.className = "contextMenu hide";
        loadContextmenu(e, 'desktopMenu');
    } else {
        contextMenu.className = "contextMenu hide";
    };

    // console.log("mouseup", e);
    !canDefault.document[e.type] && e.preventDefault();
});

document.addEventListener('mousemove', function (e) {
    let { pageX, pageY } = e;

    // 桌面鼠标选择框
    if (getComputedStyle(mouseSelectBox).display == "block") {
        let { initX, initY } = JSON.parse(mouseSelectBox.dataset.coordinate);
        mouseSelectBox.style['clip-path'] = `polygon(${initX}px ${initY}px, ${initX}px ${pageY}px, ${pageX}px ${pageY}px, ${pageX}px ${initY}px)`;
        mouseSelectBoxFN();
    };

    // 桌面程序拖拽
    let programCopy = dqS('.program-copy');
    if (programCopy) {
        let { initX, initY } = JSON.parse(programCopy.dataset.coordinate);
        programCopy.style.transform = `translate(${pageX - initX}px, ${pageY - initY}px)`;
    };

    // console.log("mousemove",e);
    !canDefault.document[e.type] && e.preventDefault();
});

document.addEventListener("drop", function (e) {
    // console.log("drop");
    let { files } = e.dataTransfer;
    // shell.readShortcutLink
    if (files.length) {
        let newProgram = new Array().map.call(files, (file, _ind) => {
            let programEl = {};
            switch (file.name.slice(file.name.lastIndexOf('.') + 1)) {
                case 'lnk':// 快捷方式
                    let lnk = shell.readShortcutLink(file.path);
                    console.log({ file, lnk });
                    programEl.name = file.name.slice(0, file.name.lastIndexOf('.'));
                    programEl.type = "program";
                    programEl.nameFN = "openlnk";
                    programEl.payload = lnk.target;
                    programEl.icon = `picture/${programEl.name}.png`;

                    programFn.execJavaGetIcon(programEl.payload, programEl.name);
                    break;

                default:
                    alert(`暂不支持引入该文件！${file.name}`);
                    break;
            };

            return programEl;
        });
        programData = [...programData, ...newProgram];
        loadDesktop();
        console.log({ programData, newProgram });
    } else {
        alert('选取的文件里包含系统文件，暂不支持引入系统文件！');
    }
    !canDefault.document[e.type] && e.preventDefault();
});

document.addEventListener("dragover", function (e) {
    // console.log("dragover",e);
    !canDefault.document[e.type] && e.preventDefault();
});



// 图片全部加载完毕时触发
Promise.all(promiseList).then((resolve) => {
    console.timeEnd("a");
    welcomePage.style.display = 'none';
    console.log("all", { resolve });
});
